import React, { useState, useEffect, useRef } from 'react';
import {
  Image,
  Popup,
} from 'antd-mobile';
import {
  DeleteOutline,
  StarFill
} from 'antd-mobile-icons';
import './index.less';
import styles from './index.less';
import Toast from 'antd-mobile/es/components/toast';
import Space from 'antd/es/space';
import { Button, Grid, Modal,Card } from 'antd-mobile';
import UnorderedListOutlined from '@ant-design/icons/lib/icons/UnorderedListOutlined';
import { Uphistory } from '@/pages/Schme/service';
import { CheckCircleOutlined, udp } from '@cscec/udp-mobile-ui';
import ExclamationCircleOutlined from '@ant-design/icons/lib/icons/ExclamationCircleOutlined';
import { updateScore } from '@/pages/Textbook/service';
import audioPlayer from '../../utils/audioPlayer';

interface SelectedLetter {
  letter: string;
  buttonIndex: number;
}

// 组件主函数
const SpellingGame = ({values,num,length,setNum,wordList}:any) => {
  // 题目数据
  const wordQuestions = values?.tbExerciseOptionVos[0]
  const unitNum = wordList[0]?.unitIdEXName.substring(0, 1)
  const [selectedLetters, setSelectedLetters] = useState<SelectedLetter[]>([]);
  const [letterPool, setLetterPool] = useState<string[]>([]);
  const [disabledLetters, setDisabledLetters] = useState<number[]>([]);
  const [showFeedback, setShowFeedback] = useState<boolean>(false);
  const [isCorrect, setIsCorrect] = useState<boolean>(false);
  const [userAnswer, setUserAnswer] = useState<string>('');
    //是否第一次选对
    const [isFirstTrue,setIsFirstTrue]=useState(true)


  // 初始化字母池
  useEffect(() => {
    generateLetterPool();
    setSelectedLetters([]);
    setDisabledLetters([]);
    setUserAnswer('');
  }, [wordQuestions]);

  // 生成字母池
  const generateLetterPool = () => {
    const answer = wordQuestions.name;
    const correctLetters = answer.split('');
    
    // 添加2-3个混淆字母
    const numDistractors = Math.floor(Math.random() * 2) + 2;
    const distractors = generateRandomLetters(numDistractors, correctLetters);
    
    // 合并并打乱
    const allLetters = [...correctLetters, ...distractors]
      .sort(() => Math.random() - 0.5);
    setLetterPool(allLetters);
  };

  // 生成随机字母
  const generateRandomLetters = (count: number, excludeLetters: string[]): string[] => {
    const alphabet = 'abcdefghijklmnopqrstuvwxyz';
    const availableLetters = alphabet.split('').filter(letter => !excludeLetters.includes(letter));
    const randomLetters: string[] = [];
    
    for (let i = 0; i < count; i++) {
      const randomIndex = Math.floor(Math.random() * availableLetters.length);
      randomLetters.push(availableLetters[randomIndex]);
    }
    
    return randomLetters;
  };

  // 选择字母
  const handleLetterClick = (letter: string, index: number) => {
    if (disabledLetters.includes(index) || selectedLetters.length >= wordQuestions.name.length) {
      return;
    }

    const newSelectedLetters = [...selectedLetters, { letter, buttonIndex: index }];
    setSelectedLetters(newSelectedLetters);
    setDisabledLetters([...disabledLetters, index]);
    
    // 更新用户答案
    const newAnswer = newSelectedLetters.map(item => item.letter).join('');
    setUserAnswer(newAnswer);
  };

  // 删除最后一个字母
  // const handleDelete = () => {
  //   if (selectedLetters.length === 0) return;
    
  //   const lastLetter = selectedLetters[selectedLetters.length - 1];
  //   const newSelectedLetters = selectedLetters.slice(0, -1);
  //   const newDisabledLetters = disabledLetters.filter(idx => idx !== lastLetter.buttonIndex);
    
  //   setSelectedLetters(newSelectedLetters);
  //   setDisabledLetters(newDisabledLetters);
    
  //   // 更新用户答案
  //   const newAnswer = newSelectedLetters.map(item => item.letter).join('');
  //   setUserAnswer(newAnswer);
  // };

  //清空用户输入单词
  const handleClear = () => {
    setSelectedLetters([]);
    setDisabledLetters([]);
    setUserAnswer('');
  };

  //控制弹窗
  const [visible, setVisible] = useState(false)
  const [visible1, setVisible1] = useState(false)
  // 所有单词弹窗
  const [modalvisible, setModalvisible] = useState(false)
    //翻页功能
  const next = async () => {
    const result = updateScore({
      unitId:values.unitId,
      type:0,
      flag:isFirstTrue?0:1
    })
    if (num + 1 > length) {
      Uphistory({
        textbookId: values.textbookId,
        unitId: values.unitId,
        topicId: values.topicId,
        exerciseId:values.id,
        completionStatus: 2, studyFlag: 1, historyType: 1
      }).then((rt) => {
        udp.message('当前主题已经学习完毕!')
        udp.close()
      })
    } else {
      //翻页时，设置回true
      setIsFirstTrue(true)
      Uphistory({
        textbookId: values.textbookId,
        unitId: values.unitId,
        topicId: values.topicId,
        exerciseId:values.id,
        completionStatus: 2,
        studyFlag: 1, historyType: 1
      })
      setNum(num + 1)
    }
  }
  const mesArr = ['Great job!', 'Awesome!！', 'Wow, so clever!', 'Perfect!', 'High five!', 'Brilliant!', 'Way to go!', 'You’re amazing!', 'Keep up the good work!']
  const index = Math.floor(Math.random() * (8))
  const errorArr = ['Oops! Try again', 'Not yet.Try again!', 'Almost! Try once more', 'Another try!', 'Not right.Try again!', 'Keep going!']
  const errIndex = Math.floor(Math.random() * (6))

  // 检查答案
  const handleCheck = () => {
    console.log(wordQuestions)
    const isAnswerCorrect = userAnswer === wordQuestions.name;
    setIsCorrect(isAnswerCorrect);
    setShowFeedback(true);
    
    if (isAnswerCorrect) {
      audioPlayer.playSuccess();//播放音效
      setVisible(true)
    } else {
      audioPlayer.playFailure()//播放音效
      setIsFirstTrue(false)//这里设置不是第一次选对了
      setVisible1(true)
    }
  };


  // 渲染拼写输入区域
  const renderSpellingInputs = () => {
    return (
      <div className={styles["spelling-inputs"]}>
        <Space wrap style={{ justifyContent: 'center', width: '100%' }}>
          {Array.from({ length: wordQuestions.name.length }).map((_, index) => (
            <div
              key={index}
              className={index < selectedLetters.length ?styles["spelling-box-filled"]: showFeedback && !isCorrect &&
                 selectedLetters[index]?.letter !== wordQuestions.name[index]?styles["spelling-box-error"]:styles["spelling-box"]}
            >
              {selectedLetters[index]?.letter.toUpperCase() || ''}
            </div>
          ))}
        </Space>
      </div>
    );
  };

  // 渲染字母池
  const renderLetterPool = () => {
    return (
      <Grid columns={5} gap={8}>
        {letterPool.map((letter, index) => (
          <Grid.Item key={index}>
            <Button
              className={disabledLetters.includes(index)?styles["letter-btn-disabled"]:styles["letter-btn"]}
              onClick={() => handleLetterClick(letter, index)}
              disabled={disabledLetters.includes(index)}
            >
              {letter.toUpperCase()}
            </Button>
          </Grid.Item>
        ))}
      </Grid>
    );
  };
    const [current, setCurrent] = useState(1)
    const handleAllWord = () => {
    setModalvisible(true)

  }

  return (
    <>
      <div className={styles["word-header"]}>
        <div className={styles["word"]}>单词{num}/{length}</div>
        <div className={styles["word"]} onClick={handleAllWord}>
          <UnorderedListOutlined />
          所有单词
        </div>

      </div>
      {/* 主内容区 */}
      <div className={styles["main-content"]}>
        {/* 图片区域 */}
        <Card className={styles["image-card"]}>
          <Image
            src={wordQuestions.imgUrl}
            className={styles["question-image"]}
            fit="contain"
          />
        </Card>

        {/* 提示文字 */}
        <div className={styles["hint-text"]}>
          请选择下方字母，拼写出图片对应的单词
        </div>

        {/* 拼写输入区 */}
        {renderSpellingInputs()}

        {/* 删除按钮 */}
        {
        // selectedLetters.length > 0 && (
        //   <div className={styles["delete-section"]}>
        //     <Button 
        //       fill="none" 
        //       size="small" 
        //       className={styles["delete-btn"]}
        //       onClick={handleClear}
        //     >
        //       <DeleteOutline />
        //       {/* 删除 */}
        //       重做
        //     </Button>
        //   </div>
        // )
        }

        {/* 字母池 */}
        <Card className={styles["letter-pool-card"]}>
          {renderLetterPool()}
        </Card>
      </div>

      {/* 底部检查按钮 */}
      <div className={styles["actions"]}>
        <Button
          size="large"
           className={styles["continue-button"]}
          disabled={selectedLetters.length !== wordQuestions.name.length}
          onClick={handleCheck}
          block
        >
          {/* {showFeedback && isCorrect ? 'NEXT' : 'CHECK'} */}
          Check
        </Button>
          <Button
          size="large"
           className={styles["continue-button"]}
          disabled={selectedLetters.length==0}
          onClick={handleClear}
          style={{
            backgroundColor:"red"
          }}
          block
        ><DeleteOutline />
          重做
        </Button>
      </div>

      {/* 反馈弹窗 */}
      <Popup
        visible={visible}
        bodyStyle={{
          height: '35vh',
          backgroundColor: '#ffffff',
          borderRadius: '25px 25px 0 0',
          textAlign: 'center',
        }}
      >
        <div
          style={{
            height: '180px',
            color: '#4caf50',
            fontSize: '30px',
            fontWeight: 'bold',
            padding: '50px'
          }}>
          <CheckCircleOutlined
            style={{
              color: '#4caf50',
              fontSize: 'xxx-large',
              display: 'block',
            }} />
          {mesArr[index]}
          <p style={{
            fontSize: 'large'
          }}>中文:{wordQuestions.answer}</p>
          </div>

        <Button
          size="large"
          onClick={() => {
            setVisible(false)
            next()
          }}
          className={styles["continue-button"]}
          style={{
            width: '90%',
            backgroundColor: '#4caf50',
            color: '#ffffff',
            margin:"0 auto"
          }}
          //disabled={!selectedImage}
          block
        >
          Next
        </Button>
      </Popup>
      <Popup
        visible={visible1}
        bodyStyle={{
          height: '35vh',
          background: '#ffffff',
          textAlign: 'center',
          borderRadius: '25px 25px 0 0'
        }}
      >
        <div
          style={{
            height: '180px',
            color: 'red',
            fontSize: '30px',
            fontWeight: 'bold',
            padding: '50px'
          }}>
          <ExclamationCircleOutlined style={{
            color: 'red',
            fontSize: 'xxx-large',
            display: 'block'
          }} />
          {errorArr[errIndex]}</div>
        <Button
          size="large"
          onClick={() => {
            setVisible1(false)
            //setSelectedImage(null)
            //next()
          }}
          className={styles["continue-button"]}
          style={{
            width: '90%',
            color: '#ffffff',
            backgroundColor: '#f44336',
            margin:"0 auto"
          }}
          //disabled={!selectedImage}
          block
        >
          Try Again
        </Button>
      </Popup>
      {/* 单词列表弹窗 */}
        <Modal visible={modalvisible}
        bodyClassName={styles["list-modal"]}
        content={
          <div className={styles["list-content"]}>
            <h3 className={styles['list-title']}>{`Unit ${unitNum}：所有单词`}</h3>
            <p className={styles['header-title']}>点击单词直接跳转学习</p>
            <div className={styles["word-list"]}>
              {wordList.map((item, index) => {
                return <div className={current === index + 1 ? styles["word-item-current"] : styles["word-item"]}
                  onClick={() => {
                    setCurrent(index + 1)
                    setNum(index + 1)
                    setModalvisible(false)
                  }}>
                    {item.type==2?<span>{item.name}</span>:<Image
                    src={item.imgUrl}
                    style={{height:"21px"}}
                    fit='contain'
                  />}
                  <StarFill className={current === index + 1 ? styles["word-inco-current"] : styles["word-inco"]} />
                </div>
              })}
            </div>
            <Button className={styles["close-button"]}
              onClick={() => {
                setModalvisible(false)
              }}>关闭</Button>
          </div >
        }

        closeOnAction
        closeOnMaskClick={true}
        onClose={() => {
          setModalvisible(false)
        }}
      >

      </Modal >
    </>
  );
};

export default SpellingGame;